package com.example.tokendemo.service;

import com.example.tokendemo.model.LoginUser;
import com.example.tokendemo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class SysLoginService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    public String login(String username, String password, String code, String uuid) {
        Authentication authentication = null;

        try {

            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                return e.toString();
            } else {
                return e.toString();
            }
        }
        //LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = new User();
        user.setPlayer_name(username);
        user.setPassword(password);
        LoginUser loginUser = new LoginUser(user,null);
        return tokenService.createToken(loginUser);
    }
}
